package com.apes.framework.plugin.esb.processor.connector.yyerp;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.esb.processor.AbstractChainProcessor;
import com.apes.framework.util.MD5Util;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.Tools;
import com.apes.oap.RopRequestContext;
import com.apes.oap.RopUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 功能：签名
 *
 * @author xul
 * @create 2019-10-23 11:57
 */
public class ApesOldSignProcessor<T extends SimpleRequest, R> extends AbstractChainProcessor<T, R> {

    private String appid;
    private String secretKey;
    private String method;

    @Override
    protected R doProcess(T request) {
        Map<String, String> headers = new HashMap();
        headers.putAll(calcPassword());
        Map data = new HashMap();
        Map m = request.getMap();
        if (m.containsKey("headers") && m.containsKey("body")) {
            headers.putAll((Map<String, String>) m.get("headers"));
            data.put("pdata", m.get("body"));
        } else {
            headers.put("method", method);
            data.put("pdata", request.getData());
        }
        return (R) MapUtil.mapper("headers", headers, "body", data);
    }


    /***
     * 计算连接yyerp的password
     * 1. 获取去除后三位的当前时间戳
     * 2. 利用密钥和当前时间戳连接并进行MD5加密
     * 3. 取加密后的前八位
     * @return
     */
    private Map calcPassword() {
        String time = String.valueOf(System.currentTimeMillis());
        time = time.substring(0, time.length() - 3);
        String password = MD5Util.encrypt(appid + secretKey + time).substring(0, 8);
        return MapUtil.mapper("time", time, "pass", password, "appid", appid);
    }

    public String getAppid() {
        return appid;
    }

    public void setAppid(String appid) {
        this.appid = appid;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }
}
